package com.pipe.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.pipe.config.OSSProperties;
import com.pipe.service.OssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


/**
 * @ClassName AiLiOssServiceImpl
 * @Author HETAO
 * @Date 2020/7/10 15:26
 */
public class AiLiOssServiceImpl implements OssService {

    private static final Logger log = LoggerFactory.getLogger(AiLiOssServiceImpl.class);

    private OSSProperties prop;

    public AiLiOssServiceImpl(OSSProperties prop) {
        this.prop = prop;
    }

    @Override
    public String uploadByOss(MultipartFile file) {
        String endpoint = prop.getEndpoint();
        String accessKeyId = prop.getAccessKey();
        String accessKeySecret = prop.getSecretKey();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String bucketName = prop.getBucketName();
        String fileName = file.getOriginalFilename();

        //日期格式化
        String date = DateUtil.parse(DateUtil.now()).toString("yyyy/MM/dd");
        //添加uuid
        fileName = date+"/"+ IdUtil.simpleUUID() + fileName;
        ossClient.putObject(bucketName,fileName, inputStream);

        ossClient.shutdown();
        String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;
    }
}
